'use strict';

define(['../../controllers', '../service/operationService', 'datepicker'], function(controllers) {
    controllers.log.register('OperationController', ['$scope', '$location', 'OperationService', function($scope, $location, operationService) {
        $scope.init = function() {
            $scope.optStartTime = '';
            $scope.optEndTime = '';
            $scope.pageNo = 1;
            $scope.pageSize = 10;
            $scope.isScheduler = ($location.path().lastIndexOf('scheduler') != -1);

            $('#query_optStartTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var oldStartTime = $scope.query_optStartTime;
                var newStartTime = e.date.getDayBeginTime();
                if ($scope.query_optEndTime > 0 && newStartTime > $scope.query_optEndTime) {
                    $scope.query_optStartTime = oldStartTime > 0 ? oldStartTime : new Date($scope.query_optEndTime).getDayBeginTime();
                    $('#query_optStartTime').val(new Date($scope.query_optStartTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_optStartTime = newStartTime;
            });

            $('#query_optEndTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var oldEndTime = $scope.query_optEndTime;
                var newEndTime = e.date.getDayEndTime();
                if ($scope.query_optStartTime> 0 && newEndTime < $scope.query_optStartTime) {
                    $scope.query_optEndTime = oldEndTime > 0 ? oldEndTime : new Date($scope.query_optStartTime).getDayEndTime();
                    $('#query_optEndTime').val(new Date($scope.query_optEndTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_optEndTime = newEndTime;
            });
        };
        $scope.query = function (pageNo) {
            if (pageNo != null) {
                $scope.pageNo = pageNo;
            }

            operationService.query({
                optStartTime : $scope.query_optStartTime,
                optEndTime: $scope.query_optEndTime,
                isScheduler: $scope.isScheduler,
                pageNo: $scope.pageNo,
                pageSize: $scope.pageSize
            }, function (data) {
                $scope.paged = data.paged;
                $scope.admins = data.admins;
            });
        };

        $scope.init();
        $scope.query();
    }]);
});